<template>
  <div class="system-user-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="769px"
    >
      <el-form
        ref="orderDialogFormRef"
        :rules="rules"
        :model="state.ruleForm"
        size="default"
        label-width="90px"
      >
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="客户公司" prop="company">
              <el-select
                v-model="state.ruleForm.company_id"
                class="m-2"
                filterable
                placeholder="请选择客户"
                size="default"
                style="width: 240px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="时间" prop="order_time">
              <el-date-picker
                v-model="state.ruleForm.order_time"
                size="default"
                type="date"
                placeholder="请选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-divider></el-divider>

          <div style="width: 100%; display: flex">
            <div>
              <el-form
                v-for="data in state.goods_list"
                :key="data"
                :model="data"
                ref="goods_list"
                label-width="110px"
              >
                <el-row>
                  <el-col :span="11">
                    <el-form-item label="存货名称" prop="name">
                      <el-select
                        v-model="data.goods"
                        class="m-2"
                        filterable
                        placeholder="请选择商品"
                        size="default"
                        style="width: 240px"
                      >
                        <el-option
                          v-for="item in g_options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="数量" prop="sex">
                      <el-input v-model="data.num" size="samll"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item label="金额" prop="sex">
                      <el-input v-model="data.price" size="samll"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div style="width: 150px; margin-top: 5px">
              <el-button @click="adds">+</el-button>
              <el-button @click="reduce" :disabled="state.flag">-</el-button>
            </div>
          </div>
          <el-divider></el-divider>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="金额合计" prop="amount">
              <el-input
                v-model="state.ruleForm.amount"
                placeholder=""
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="送货电话" prop="deliver_tel">
              <el-input
                v-model="state.ruleForm.deliver_tel"
                placeholder="请输入送货电话"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="送货人" prop="carrier">
              <el-input
                v-model="state.ruleForm.carrier"
                placeholder="请输入送货人"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="接货人" prop="receiving">
              <el-input
                v-model="state.ruleForm.receiving"
                placeholder="请输入接货人"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="送货地址" prop="address">
              <el-input
                v-model="state.ruleForm.address"
                placeholder="请输入送货地址"
                maxlength="150"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="备注" prop="note">
              <el-input
                v-model="state.ruleForm.note"
                type="textarea"
                placeholder="备注"
                maxlength="150"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addnum" size="default">计 算</el-button>
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{
            state.dialog.submitTxt
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="orderDialogFormRef">
import { reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { add, update, get_one } from "/@/api/order/index";
import { company_type_sel } from "/@/api/company/index";
import { goods_type_sel, get_goods_list } from "/@/api/goods/index";
import type { FormInstance, FormRules } from "element-plus";
interface RuleForm {
  name: string;
  tel: string;
}
// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);

const options = ref();
const g_options = ref();

// 定义变量内容
const orderDialogFormRef = ref();
const state = reactive({
  goods_list: [
    {
      goods: "",
      num: 0,
      price: 0,
    },
  ],
  flag: true,
  ruleForm: {
    id: "",
    order_time: "",
    company_id: "",
    goods: "",
    unit: "",
    price: "",
    num: 0,
    amount: 0,
    deliver_tel: "18561701598",
    carrier: "王集平",
    receiving: "",
    note: "",
    address: "龙口市嘉园批发市场成润肉食",
  },
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: "",
  },
});

const addnum = () => {
  state.ruleForm.amount = 0;
  for (let index = 0; index < state.goods_list.length; index++) {
    const element = state.goods_list[index];
    for (let i = 0; i < g_options.value.length; i++) {
      const g_element = g_options.value[i];
      if (element.goods == g_element.value) {
        element.price = g_element.label.split(":")[1] * element.num;
        element.price = parseFloat(element.price.toFixed(2));
      }
    }
    state.ruleForm.amount = parseFloat(
      (state.ruleForm.amount + element.price).toFixed(2)
    );
  }
};
const timeDefault = () => {
  var getTime = new Date().getTime(); //获取到当前时间戳
  var time = new Date(getTime);
  var year = time.getFullYear(); // 年
  var month = (time.getMonth() + 1).toString().padStart(2, "0"); // 月
  var date = time.getDate().toString().padStart(2, "0"); // 日
  var hour = time.getHours().toString().padStart(2, "0"); // 时
  var minute = time.getMinutes().toString().padStart(2, "0"); // 分
  var second = time.getSeconds().toString().padStart(2, "0"); // 秒

  state.ruleForm.order_time = year + "-" + month + "-" + date;
};
// 表单添加一行
const adds = () => {
  if (state.goods_list.length < 6) {
    var arr: any = { goods: "", num: "", price: "" };
    state.goods_list.push(arr);
    flags();
  }
};
// 表单减少一行
const reduce = () => {
  state.goods_list.length = state.goods_list.length - 1;
  flags();
};
// 判断数组长度
const flags = () => {
  if (state.goods_list.length < 2) {
    state.flag = true;
  } else {
    //先赋值为true再赋为false, 不然会没反应
    state.flag = true;
    state.flag = false;
  }
};

// 重置方法
const resetForm = () => {
  state.goods_list = [
    {
      goods: "",
      num: 0,
      price: 0,
    },
  ];
};
const rules = reactive<FormRules<RuleForm>>({
  name: [{ trigger: "blur" }],
  tel: [{ trigger: "blur" }],
});
// 打开弹窗
const openDialog = (type: string, row: any) => {
  state.dialog.type = type;
  if (type === "edit") {
    // state.ruleForm = row;

    state.dialog.title = "修改订单";
    state.dialog.submitTxt = "修 改";
    get_one(row.id).then((res) => {
      state.ruleForm.id = res.data.id;
      state.ruleForm.company_id = res.data.company_id;
      state.ruleForm.amount = res.data.amount;
      state.ruleForm.carrier = res.data.carrier;
      state.ruleForm.address = res.data.address;
      state.ruleForm.deliver_tel = res.data.deliver_tel;
      state.ruleForm.note = res.data.note;
      state.ruleForm.order_time = res.data.order_time;
      state.ruleForm.receiving = res.data.receiving;
      state.goods_list = JSON.parse(res.data.goods_list);
      flags();
    });
  } else {
    resetForm();
    state.dialog.title = "新增订单";
    state.dialog.submitTxt = "新 增";
  }
  state.dialog.isShowDialog = true;
  company_type_sel().then((res) => {
    options.value = res.data;
  });
  goods_type_sel().then((res) => {
    g_options.value = res.data;
  });
  timeDefault();
};
// 关闭弹窗
const closeDialog = () => {
  orderDialogFormRef.value.resetFields();
  state.dialog.isShowDialog = false;
  emit("refresh");
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = () => {
  // 将 order.fbaPo 转换为数组类型
  addnum();
  const goods_list = JSON.stringify(state.goods_list);
  if (state.dialog.type === "add") {
    add(
      state.ruleForm.company_id,
      state.ruleForm.order_time,
      goods_list,
      state.ruleForm.amount,
      state.ruleForm.deliver_tel,
      state.ruleForm.carrier,
      state.ruleForm.receiving,
      state.ruleForm.note,
      state.ruleForm.address
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success(res.msg);
        closeDialog();
      }
    });
  } else {
    update(
      state.ruleForm.id,
      state.ruleForm.company_id,
      state.ruleForm.order_time,
      goods_list,
      state.ruleForm.amount,
      state.ruleForm.deliver_tel,
      state.ruleForm.carrier,
      state.ruleForm.receiving,
      state.ruleForm.note,
      state.ruleForm.address
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success(res.msg);
        closeDialog();
      }
    });
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
